import React, { JSX } from 'react';
import { NulDialog, NulCommonOperations, NulFormItem } from '../../components/NulDialog';
import { Autocomplete, FormControl, TextField } from '@mui/material';
import { useAppDispatch, useAppSelector } from '../../actions/hooks';
import { selectWarehouseTypes, selectWarehouseTypesLoaded, warehouseManagementActions } from '../../actions/WarehouseManagement';

interface CreateWarehouseProps {
  open: boolean;
  onClose: () => void;
}

function CreateWarehouse(props: CreateWarehouseProps): JSX.Element {
  const { open, onClose } = props;

  const [name, setName] = React.useState<string>('');
  const [type, setType] = React.useState<string>('');
  const [address, setAddress] = React.useState<string>('');

  const dispatch = useAppDispatch();

  const warehouseTypes = useAppSelector(selectWarehouseTypes);
  const warehouseTypesLoaded = useAppSelector(selectWarehouseTypesLoaded);

  const clear = () => {
    setName('');
    setType('');
    setAddress('');
  }

  const onCreateClicked = () => {
    dispatch(warehouseManagementActions.createWarehouse({ name, type, address }));
    onClose();
    clear();
  };

  React.useEffect(() => {
    if (!warehouseTypesLoaded) {
      dispatch(warehouseManagementActions.getWarehouseTypes());
    }
  }, [warehouseTypesLoaded, dispatch]);

  return (
    <NulDialog
      open={open}
      onClose={onClose}
      title='Create New Warehouse'
      operations={
        <NulCommonOperations
          onPositiveClicked={onCreateClicked}
          onNegativeClicked={onClose}
          positiveText='Create'
        />
      }
    >
      <NulFormItem hint='Name' component={
        <TextField placeholder='Name' fullWidth={true} size='small' value={name} onChange={(event) => { setName(event.target.value); }} />
      } />
      <NulFormItem hint='Type' component={
        <FormControl fullWidth size='small'>
          <Autocomplete
            options={warehouseTypes}
            size='small'
            fullWidth={true}
            getOptionLabel={option => option}
            renderInput={(params) => <TextField {...params} />}
            value={type}
            onChange={(event, value) => {
              setType(value ?? '');
            }}
          />
        </FormControl>
      } />
      <NulFormItem hint='Address' component={
        <TextField placeholder='Address' fullWidth={true} size='small' value={address} onChange={(event) => { setAddress(event.target.value); }} />
      } />
    </NulDialog>
  );
}

export { CreateWarehouse };